//
//  AddSosContactsViewController.m
//  Leo01
//
//  Created by 张旭 on 15/9/27.
//  Copyright (c) 2015年 张旭. All rights reserved.
//

#import "AddSosContactsViewController.h"
#import "AppDelegate.h"

#import "SyncManager.h"
#import "DataManager.h"
#import "LeoMsg.h"

@interface AddSosContactsViewController ()

@property (nonatomic,retain) SyncManager *syncManager;
@property (nonatomic,retain) DataManager *dataManager;

@end

@implementation AddSosContactsViewController

@synthesize navLeftButton;
@synthesize navRightButton;
@synthesize tableView;
@synthesize tableViewHeight;
@synthesize addSosListTableViewCell;
@synthesize tableArray;

@synthesize syncManager;
@synthesize dataManager;
@synthesize contactTableArray;
static int totalSelectNum;
static int SOScount=0;
static int i=0;

-(void)dealloc
{
    syncManager=NULL;
    dataManager=NULL;
    contactTableArray=NULL;
}
- (void)viewDidLoad {

    [super viewDidLoad];
    self.extendedLayoutIncludesOpaqueBars = YES;
    self.title=@"添加紧急联系人";
    self.navigationItem.rightBarButtonItem=self.navRightButton;
    
    totalSelectNum=0;
    
    [self initNavButton];
    [self initDataProxy];
    [self worktable];
    [self combineData];
    
    // Do any additional setup after loading the view from its nib.
}
-(void)initDataProxy{
    self.syncManager=[[SyncManager alloc] init];
    self.dataManager=[[DataManager alloc] init];
}
- (void)initNavButton {

    [navLeftButton setTarget:self];
    [navLeftButton setAction:@selector(back)];
    
    [navRightButton setTarget:self];
    [navRightButton setAction:@selector(saveSosContact)];

}

- (void)back{

    [self.navigationController popViewControllerAnimated:YES];
    //[self dismissViewControllerAnimated:YES completion:nil];

}

- (void)saveSosContact{

    //save
    UIActivityIndicatorView *loadingView=[LeoMsg showLoadingView];
    [self.view addSubview:loadingView];
    [loadingView startAnimating];
    SOScount=0;//初始个数
    for (i=0;i<ChooseStatusArray.count;i++)
    {
        
        if ([[ChooseStatusArray objectAtIndex:i] isEqualToNumber:[NSNumber numberWithInt:1]]) {
            
            if ([[self.tableArray objectAtIndex:i] isKindOfClass:[Contact class]])
            {
                Contact *contact=[self.tableArray objectAtIndex:i];
                contact.type=1;
                [self.syncManager setWatchContact:contact completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
                    if(result==SUCESS)
                    {
                        SOScount=SOScount+1;
                        if (SOScount==ChooseStatusArray.count)
                        {
                            [loadingView stopAnimating];
                            [LeoMsg showMsg:@"添加紧急联系人成功"];
                            [self.navigationController popViewControllerAnimated:YES];
                        }

                    }
                    else {
                        [Tooler showHttpMsg:result description:description msg:@"添加紧急联系人失败1"];
                        [loadingView stopAnimating];
                        return ;
                    }
                }];

            }
            else
            {
                if ([[self.tableArray objectAtIndex:i] isKindOfClass:[Manager class]])
                {
                    Manager *manager=[self.tableArray objectAtIndex:i];
                    if (manager.type==1){
                        SOScount=SOScount+1;
                        if (SOScount==ChooseStatusArray.count)
                        {
                            [loadingView stopAnimating];
                            [LeoMsg showMsg:@"添加紧急联系人成功"];
                            [self.navigationController popViewControllerAnimated:YES];
                        }
                    }
                    if (manager.type!=1){
                        User *user=[User sharedSingleton];
                        NSString *userId=user.uid;
                        Watch *watch=[self.dataManager getActiveWatch:userId];
                        NSString *watchId=watch.deviceUid;
                        manager.isSos=1;
                        [self.syncManager updateViceAdminInfo:watchId viceAdmin:manager completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
                            if(result==SUCESS)
                            {
                                SOScount=SOScount+1;
                                if (SOScount==ChooseStatusArray.count)
                                {
                                    [loadingView stopAnimating];
                                    [LeoMsg showMsg:@"添加紧急联系人成功"];
                                    [self.navigationController popViewControllerAnimated:YES];
                                }

                            }
                            else {
                                [Tooler showHttpMsg:result description:description msg:@"添加紧急联系人失败2"];
                                [loadingView stopAnimating];
                                return ;
                            }
                        }];

                    }}
            }
        }
        
        
    if ([[ChooseStatusArray objectAtIndex:i] isEqualToNumber:[NSNumber numberWithInt:0]]) {
            if ([[self.tableArray objectAtIndex:i] isKindOfClass:[Contact class]])
            {
                Contact *contact=[self.tableArray objectAtIndex:i];
                contact.type=0;
                [self.syncManager setWatchContact:contact completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
                    if(result==SUCESS)
                    {
                        SOScount=SOScount+1;
                        if (SOScount==ChooseStatusArray.count)
                        {
                            [loadingView stopAnimating];
                            [LeoMsg showMsg:@"添加紧急联系人成功"];
                            [self.navigationController popViewControllerAnimated:YES];
                        }
                        

                    }
                    else{

                        [Tooler showHttpMsg:result description:description msg:[@"添加紧急联系人失败" stringByAppendingString:contact.contactname]];
                        [loadingView stopAnimating];
                        return ;
                    }
                }];
                
            }
            else
            {
                if ([[self.tableArray objectAtIndex:i] isKindOfClass:[Manager class]])
                {
                    Manager *manager=[self.tableArray objectAtIndex:i];
                    if (manager.type==1){
                        SOScount=SOScount+1;
                        if (SOScount==ChooseStatusArray.count)
                        {
                            [loadingView stopAnimating];
                            [LeoMsg showMsg:@"添加紧急联系人成功"];
                            [self.navigationController popViewControllerAnimated:YES];
                        }
                    }
                    if (manager.type!=1){
                        User *user=[User sharedSingleton];
                        NSString *userId=user.uid;
                        Watch *watch=[self.dataManager getActiveWatch:userId];
                        NSString *watchId=watch.deviceUid;
                        manager.isSos=0;
                        [self.syncManager updateViceAdminInfo:watchId viceAdmin:manager completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
                            if(result==SUCESS)
                            {
                               SOScount=SOScount+1;
                                if (SOScount==ChooseStatusArray.count)
                                {
                                    [loadingView stopAnimating];
                                    [LeoMsg showMsg:@"添加紧急联系人成功"];
                                    [self.navigationController popViewControllerAnimated:YES];
                                }

                            }
                            else {
                                [Tooler showHttpMsg:result description:description msg:@"添加紧急联系人失败4"];
                                [loadingView stopAnimating];
                                return ;
                            }
                        }];
                        
                    }}
            }
   
        }
    }
    
    
}

-(void)worktable{

    self.automaticallyAdjustsScrollViewInsets=NO;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.rowHeight = UITableViewAutomaticDimension;
    tableView.delegate=self;
    tableView.dataSource=self;
    
    UINib *cellAddSosList = [UINib nibWithNibName:@"AddSosListTableViewCell" bundle:nil];
    [tableView registerNib:cellAddSosList forCellReuseIdentifier:@"addsoslisttableviewcell"];
    self.addSosListTableViewCell  = [tableView dequeueReusableCellWithIdentifier:@"AddSosListTableViewCell"];

}

-(void)combineData{
    NSLog(@"Combine Data begin");

    self.tableArray = [[NSMutableArray alloc]init];
    self.contactTableArray=[[NSMutableArray alloc]init];
    ChooseStatusArray = [[NSMutableArray alloc]init];
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
//    for (int i = 0; i < myDelegate.ManagerDetailsDataArray.count; i++) {
//        [self.tableArray addObject:[myDelegate.ManagerDetailsDataArray objectAtIndex:i]];
//        [ChooseStatusArray addObject:[NSNumber numberWithInt:0]];
//        
//    }
//    NSLog(@"Combine Data middle");


//    for (int i = 0; i < myDelegate.ContactsDetailsDataArray.count; i++) {
//        [self.tableArray addObject:[myDelegate.ContactsDetailsDataArray objectAtIndex:i]];
//        
//        NSDictionary *dic=[self.tableArray objectAtIndex:i];
//        Contact *contact1=[self.dataManager getContact:[dic valueForKey:@"contact_id"]];
//       // [self.contactTableArray addObject:contact1];
//        if (contact1.type==4) { [ChooseStatusArray addObject:[NSNumber numberWithInt:1]];}//4代表紧急联系人 3是普通 2是副管理员 1是主管理员
//        else{
//            if (contact1.type==1) { [ChooseStatusArray addObject:[NSNumber numberWithInt:1]];}
//            else{
//                [ChooseStatusArray addObject:[NSNumber numberWithInt:0]];}
//        }
//    }
    

    User *user=[User sharedSingleton];
    NSString *userId=user.uid;
    Watch *watch=[self.dataManager getActiveWatch:userId];
    NSString *watchId=watch.deviceUid;
    self.tableArray=[self.dataManager getContactLists:watchId accountId:userId];
    for (int i=0;i<tableArray.count;i++)
    {
    if ([[self.tableArray objectAtIndex:i] isKindOfClass:[Contact class]])
    {
        Contact *contact=[self.tableArray objectAtIndex:i];
        if (contact.type==0){[ChooseStatusArray addObject:[NSNumber numberWithInt:0]];}
        else{[ChooseStatusArray addObject:[NSNumber numberWithInt:1]];totalSelectNum=totalSelectNum+1;}
    }
    else
    {
        if ([[self.tableArray objectAtIndex:i] isKindOfClass:[Manager class]])
        {
            Manager *manager=[self.tableArray objectAtIndex:i];
            if (manager.type==1){[ChooseStatusArray addObject:[NSNumber numberWithInt:1]];totalSelectNum=totalSelectNum+1;}
            else
            {
                if (manager.isSos==0){[ChooseStatusArray addObject:[NSNumber numberWithInt:0]];}
                else{[ChooseStatusArray addObject:[NSNumber numberWithInt:1]];totalSelectNum=totalSelectNum+1;}
            }
        }
    }
    }
    NSLog(@"Combine Data Finish");
    
}

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.view.window==nil)
    {
        self.view=nil;
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 80;

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    CGRect rect = [UIScreen mainScreen].bounds;
    if (80 * (tableArray.count) < rect.size.height) {
        tableViewHeight.constant = 80 * (tableArray.count);
    }
    else
        tableViewHeight.constant = rect.size.height - 80;
    return tableArray.count;

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    AddSosListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"addsoslisttableviewcell"];
    cell.navController=self.navigationController;
    //cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    
    //cell = [cell getandSetData:[self.tableArray objectAtIndex:indexPath.row]];
    
        if ([[self.tableArray objectAtIndex:indexPath.row] isKindOfClass:[Contact class]])
        {
            cell=[cell getandSetDataByContact:[self.tableArray objectAtIndex:indexPath.row]];
        }
        else
        {
            if ([[self.tableArray objectAtIndex:indexPath.row] isKindOfClass:[Manager class]])
            {
                cell=[cell getandSetDataByManager:[self.tableArray objectAtIndex:indexPath.row]];
            }
        }
    
    
    
    //cell=[cell getandSetData:[contactTableArray objectAtIndex:indexPath.row]];
    //    cell.alertOnOff.tag = indexPath.row + 1200;
//    [cell.alertOnOff addTarget:self action:@selector(OnAndOffAction:) forControlEvents:UIControlEventValueChanged];
    
    if ([[ChooseStatusArray objectAtIndex:indexPath.row] isEqualToNumber:[NSNumber numberWithInt:0]]) {
       [cell setChooseStatus:NO];
    }else{ [cell setChooseStatus:YES];}

    cell=[self addCellLine:cell forIndex:indexPath.row];
    return cell;

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    AddSosListTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    if ([[self.tableArray objectAtIndex:indexPath.row] isKindOfClass:[Contact class]])
    {
        Contact *contact1=[self.tableArray objectAtIndex:indexPath.row];
    }
    else
    {
        if ([[self.tableArray objectAtIndex:indexPath.row] isKindOfClass:[Manager class]])
        {
            //cell=[cell getandSetDataByManager:[self.tableArray objectAtIndex:indexPath.row]];
            Manager *manager=[self.tableArray objectAtIndex:indexPath.row];
            if (manager.type==1)
            {
               [LeoMsg showMsg:@"主管理员必须为紧急联系人"];
                return;
            }
        }
    }

    
    
//    NSDictionary *dic=[self.tableArray objectAtIndex:indexPath.row];
//    Contact *contact1=[self.dataManager getContact:[dic valueForKey:@"contact_id"]];
//    // [self.contactTableArray addObject:contact1];
//    if (contact1.type==1) {
//        [LeoMsg showMsg:@"主管理员必须为紧急联系人"];
//        return;
//        }//4代表紧急联系人 3是普通 2是副管理员 1是主管理员
    
    
    if ([[ChooseStatusArray objectAtIndex:indexPath.row] isEqualToNumber:[NSNumber numberWithInt:0]]) {
        if (totalSelectNum==3)
        {
            //超过3个不能选择
            [LeoMsg showMsg:@"不能选择超过3个紧急联系人"];
            return;
        }
        [ChooseStatusArray replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithInt:1]];
        [cell setChooseStatus:YES];
        totalSelectNum=totalSelectNum+1;
    }
    else if([[ChooseStatusArray objectAtIndex:indexPath.row] isEqualToNumber:[NSNumber numberWithInt:1]]) {
        [ChooseStatusArray replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithInt:0]];
        [cell setChooseStatus:NO];
        totalSelectNum=totalSelectNum-1;
    }
    
}

-(UITableViewCell *)addCellLine:(UITableViewCell *)cell forIndex:(int)index
{
    UILabel *line;
    if (index==tableArray.count-1)
    {
        NSLog(@"有最后一条！");
        line=[[UILabel alloc]initWithFrame:CGRectMake(0, cell.frame.size.height-1, [UIScreen mainScreen].bounds.size.width-0, 1)];
    }
    else
    {
        line=[[UILabel alloc]initWithFrame:CGRectMake(20, cell.frame.size.height-1, [UIScreen mainScreen].bounds.size.width-20, 1)];
    }
    line.backgroundColor=[UIColor colorWithRed:226/255.0 green:226/255.0 blue:228/255.0 alpha:1.0];
    
    [cell addSubview:line];
    
    return cell;
}
@end
